import { AccountType } from '~/constants/AccountType'
import { TokenType } from '~/constants/TokenType'
import { getJsApiTicket } from '~/data/token'
import { Account, Token } from '~/db'

async function refreshToken() {
    //获取所有待刷新的公众号
    const accounts = await Account.findAll({
        where: {
            type: AccountType.Mp,
        },
    })

    for (const account of accounts) {
        //检查access_token
        const token_row = await Token.findOne({
            where: {
                app_id: account.app_id,
                component_app_id: account.component_app_id,
                type: TokenType.JsapiTicket,
            },
        })

        if (token_row && token_row.expire_time!.valueOf() > Date.now() + 300000) {
            //不需要刷新的记录
            continue
        }

        await getJsApiTicket(account.app_id, account.component_app_id, true)
    }
}

refreshToken()
    .then(() => {})
    .catch((err) => {
        console.error(err)
    })
    .finally(() => process.exit())
